/*
 *       Copyright (c) 2008-2009 All rights reserved
 *               Asemantics S.r.l
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by
 *        Asemantics S.r.l."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    This product includes software developed by Asemantics S.r.l.
 *    the Semantic Web company, Rome, London, Leiden and its contributors.
 *
 * 5. Neither the name of the company nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
package com.asemantics.poco.services;

import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.asemantics.poco.Response;
import com.asemantics.poco.query.Format;
import com.asemantics.poco.query.Query;
import com.asemantics.poco.serializer.AbstractPoCoSerializer;
import com.asemantics.poco.serializer.PoCoSerializerException;
import com.asemantics.poco.serializer.json.JsonPoCoSerializer;
import com.asemantics.poco.serializer.xml.XmlPoCoSerializer;

/**
 * 
 * @author Simone Tripodi
 * @version $Id: AbstractPoCoServlet.java 219 2009-12-19 20:36:37Z simone.tripodi@gmail.com $
 */
public abstract class AbstractPoCoServlet extends HttpServlet {

    private final static String JSON_MIME = "application/json";

    private final static String XML_MIME = "application/xml";

    private static final long serialVersionUID = 1L;

    private final static Pattern ALL = Pattern.compile("/@me/@all");

    private final static Pattern USER = Pattern.compile("/@me/@all/(.+)");

    private final static Pattern SELF = Pattern.compile("/@me/@self");

    private final Logger logger = Logger.getLogger(this.getClass().getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // check first if the user is authenticated
        String currentLoggedUserId;
        try {
            currentLoggedUserId = this.getCurrentLoggedUserId(req);
        } catch (Exception e) {
            if (this.logger.isLoggable(Level.SEVERE)) {
                this.logger.log(Level.SEVERE,
                        "An error occurred while retrieving the surrent logged user id",
                        e);
            }
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
            return;
        }

        Response response;

        String requestURL = req.getRequestURL().toString();
        String pathInfo = req.getPathInfo();

        Query query;
        try {
            query = new QueryBuilder().addFilter(req)
                .addPagination(req)
                .addPresentation(req)
                .addSorting(req)
                .getQuery();
        } catch (BadRequestException e) {
            if (this.logger.isLoggable(Level.SEVERE)) {
                this.logger.log(Level.SEVERE,
                        "Impossible to serve WRONG request " + requestURL,
                        e);
            }
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        if (ALL.matcher(pathInfo).matches()) {
            try {
                response = this.getAllContactInfo(currentLoggedUserId, query);
            } catch (Exception e) {
                if (this.logger.isLoggable(Level.SEVERE)) {
                    this.logger.log(Level.SEVERE,
                            "Impossible to serve request " + requestURL,
                            e);
                }
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }
        } else if (SELF.matcher(pathInfo).matches()) {
            try {
                response = this.getSelfInfo(currentLoggedUserId, query);
            } catch (Exception e) {
                if (this.logger.isLoggable(Level.SEVERE)) {
                    this.logger.log(Level.SEVERE,
                            "Impossible to serve request " + requestURL,
                            e);
                }
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }
        } else {
            Matcher matcher = USER.matcher(pathInfo);
            if (matcher.matches()) {
                String id = matcher.group(1);
                try {
                    response = this.getUserInfo(currentLoggedUserId, id, query);
                } catch (Exception e) {
                    if (this.logger.isLoggable(Level.SEVERE)) {
                        this.logger.log(Level.SEVERE,
                                "Impossible to serve request " + requestURL,
                                e);
                    }
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    return;
                }
            } else {
                if (this.logger.isLoggable(Level.SEVERE)) {
                    this.logger.severe("Impossible to serve WRONG request "
                            + requestURL + ", path info not allowed");
                }
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
        }

        if (response == null || response.getTotalResults() == 0) {
            if (this.logger.isLoggable(Level.SEVERE)) {
                this.logger.severe("Impossible to find contacts for request "
                        + requestURL);
            }
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        OutputStream outputStream = resp.getOutputStream();
        AbstractPoCoSerializer serializer;
        if (query.getPresentation().getFormat() == Format.json) {
            serializer = new JsonPoCoSerializer(outputStream);
            resp.setContentType(JSON_MIME);
        } else {
            serializer = new XmlPoCoSerializer(outputStream);
            resp.setContentType(XML_MIME);
        }

        try {
            serializer.serialize(response);
        } catch (PoCoSerializerException e) {
            if (this.logger.isLoggable(Level.SEVERE)) {
                this.logger.log(Level.SEVERE,
                        "Impossible to serve request " + requestURL,
                        e);
            }
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    protected abstract String getCurrentLoggedUserId(final HttpServletRequest req) throws Exception;

    protected abstract Response getAllContactInfo(final String userId, final Query query) throws PoCoServletException;

    protected abstract Response getUserInfo(final String userId, final String id, final Query query) throws PoCoServletException;

    protected abstract Response getSelfInfo(final String userId, final Query query) throws PoCoServletException;

}
